﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;
using uTorrentRemote.Net;
using System.Collections.Specialized;
using System.Threading;
using System.IO;

namespace uTorrentRemote.TokenDispatchers
{
    public abstract class CommonTokenDispatcher
    {
        protected ILog log;
        public CommonTokenDispatcher(ILog log)
        {
            this.log = log;
        }

        protected bool isInitiated = false;

        protected virtual void init()
        {
            Thread thread = new Thread(new ThreadStart(worker));
            thread.Start();

            isInitiated = true;
        }

        protected string getPath()
        {
            string directory = ConfigurationManager.AppSettings["store_directory"];

            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            DateTime now = DateTime.Now;
            string filename = String.Format("{0:D4}-{1:D2}-{2:D2}_{3:D2}-{4:D2}-{5:D2}_{6}.torrent", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond);
            string path = Path.Combine(directory, filename);

            return path;
        }

        protected WebClientEx client = null;
        
        protected virtual void worker()
        {
            relogin();

            while (2 + 2 == 4)
            {
                foreach (string url in urls.Keys.ToList()) // "ToList()" is to avoid "Collection was modified; enumeration operation may not execute." exception
                {
                    if (urls[url] == false)
                    {
                        // if we can't download a file, may be it's login issue?
                        if (!tryUrl(url, 3))
                        {
                            log.Write("3 unsuccessful attempts, waiting for 3 minutes, relogin and try again");
                            Thread.Sleep(3 * 60 * 1000);
                            relogin(); // try to relogin
                            tryUrl(url, 2);
                        }
                        urls[url] = true;
                    }
                }

                Thread.Sleep(5 * 1000);
            }
        }

        protected abstract void relogin();
        protected abstract bool tryUrl(string url, int maxTries);

        // dictionary:
        // url | flag
        // where
        // url  - url to be loaded
        // flag - shows if url has been already loaded

        protected Dictionary<string, bool> urls = new Dictionary<string, bool>();
    
    }
}
